package com.crane.oss.web.controller.sports;


import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.crane.common.core.dto.MultiResponse;
import com.crane.common.core.dto.SingleResponse;
import com.crane.common.core.exception.AppException;
import com.crane.common.core.exception.BasicErrorCode;
import com.crane.common.core.utils.CollectionUtil;
import com.crane.common.core.utils.StringUtil;
import com.crane.common.framework.utils.BeanUtil;
import com.crane.common.framework.utils.DateUtil;
import com.crane.oss.school.dao.ClassesInfoDao;
import com.crane.oss.school.dao.TeacherCycleDao;
import com.crane.oss.school.dao.TestCycleDao;
import com.crane.oss.school.model.ClassesInfo;
import com.crane.oss.school.model.TeacherCycle;
import com.crane.oss.school.model.TestCycle;
import com.crane.oss.sports.XunFeiClassCourseAnalysisApiService;
import com.crane.oss.sports.bean.response.course.*;
import com.crane.oss.sports.bean.resquest.*;
import com.crane.oss.web.BaseBusinessController;
import com.crane.oss.xunfei.req.*;
import com.crane.oss.xunfei.resp.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author bealon
 */
@Api(value = "CourseAnalysisController", tags = {"智慧体育-体育课堂"})
@RestController
@RequestMapping("/sports/course")
public class CourseAnalysisController extends BaseBusinessController {

    @Resource
    HttpServletResponse httpServletResponse;

    @Resource
    XunFeiClassCourseAnalysisApiService xunFeiClassCourseAnalysisApiService;

    @Resource
    protected ClassesInfoDao classesInfoDao;

    @Resource
    protected TeacherCycleDao teacherCycleDao;


    @ApiOperation(value = "课堂记录-获取体育课堂列表", notes = "课堂记录-获取体育课堂列表")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "QueryCourseListReq")
    @PostMapping("/index")
    @ResponseBody
    public SingleResponse<Map<String, List<CourseResp>>> baseCourse(@RequestBody QueryCourseListReq request) {
        QueryClassAnalysisIndexReq queryClassAnalysisIndexReq = new QueryClassAnalysisIndexReq();
        if (CollectionUtil.isNotEmpty(request.getClassIdList())) {
            queryClassAnalysisIndexReq.setClassIds(String.join(",", request.getClassIdList()));
        } else {
            queryClassAnalysisIndexReq.setCampusId(request.getSchoolId());
        }
        queryClassAnalysisIndexReq.setMonth(DateUtil.format("yyyy年MM月", request.getDate()));
        ApiListResponse<ClassCourseAnalysisIndexResp> response = xunFeiClassCourseAnalysisApiService.getAnalysisClassCourseIndex(queryClassAnalysisIndexReq, getPartyId().toString(), null, getUserId().toString());
        if (response.getMsg().equals("success")) {
            Map<String, List<CourseResp>> map = response.getData().stream().map(s -> {
                CourseResp a = new CourseResp();
                a.setClassId(s.getClassId());
                a.setClassType(s.getClassType());
                a.setCourseId(s.getTeachCourseId());
                a.setCourseName(s.getClassName());
                a.setDayTime(s.getDayTime());
                a.setStartTime(s.getBeginTime());
                a.setEndTime(s.getEndTime());
                a.setHeartMonitor(s.getHeartMonitor());
                a.setCourseStyle(s.getCourseStyle());
                a.setStudentAttendance(s.getStudentAttendance());
                a.setCourseExam(s.getCourseExam());
                return a;
            }).collect(Collectors.groupingBy(CourseResp::getDayTime));
            return SingleResponse.of(map);
        }
        return SingleResponse.of(new HashMap<>());
    }


    @ApiOperation(value = "课堂记录-课程列表-课程首页", notes = "课堂记录-课程详情")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "QueryCourseAnalyzeReq")
    @PostMapping("/test/statistic")
    @ResponseBody
    public SingleResponse<ClassCourseAnalysisDetailResp> testStatistic(@RequestBody QueryCourseAnalyzeReq request) {
        ClassCourseAnalysisDetailResp resp = new ClassCourseAnalysisDetailResp();
        QueryAnalysisClassCourseIdReq queryAnalysisClassCourseIdReq = new QueryAnalysisClassCourseIdReq();
        queryAnalysisClassCourseIdReq.setCourseId(request.getCourseId());
        ApiSingleResponse<ClassCourseIdAnalysisResp> response = xunFeiClassCourseAnalysisApiService.getAnalysisClassCourseId(queryAnalysisClassCourseIdReq, getPartyId().toString(), null, getUserId().toString());
        if (response.getMsg().equals("success")) {
            BeanUtil.copyProperties(response.getData(), resp);
            if(StringUtil.isNotEmpty(response.getData().getClassId())){
                ClassesInfo classesInfo = classesInfoDao.selectById(Long.valueOf(response.getData().getClassId()));
                if (null != classesInfo) {
                    resp.setGrade(classesInfo.getGrade());
                }
            }
            HeartMonitorResp heartMonitorResp = new HeartMonitorResp();
            BeanUtil.copyProperties(response.getData().getHeartMonitor(), heartMonitorResp);
            resp.setHeartMonitor(heartMonitorResp);
        }
        return SingleResponse.of(resp);
    }

    @ApiOperation(value = "课堂记录-课程详情", notes = "课堂记录-课程详情")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "QueryCourseAnalyzeReq")
    @PostMapping("/record/info")
    @ResponseBody
    public SingleResponse<ClassCourseIdAnalysisInfoResp> recordInfo(@RequestBody QueryCourseAnalyzeReq request) {
        ClassCourseIdAnalysisInfoResp resp = new ClassCourseIdAnalysisInfoResp();
        QueryAnalysisClassCourseIdReq queryAnalysisClassCourseIdReq = new QueryAnalysisClassCourseIdReq();
        queryAnalysisClassCourseIdReq.setCourseId(request.getCourseId());
        ApiSingleResponse<ClassCourseIdIndexAnalysisResp> response = xunFeiClassCourseAnalysisApiService.getAnalysisClassCourseIndex(queryAnalysisClassCourseIdReq, getPartyId().toString(), null, getUserId().toString());
        if (response.getMsg().equals("success")) {
            BeanUtil.copyProperties(response.getData(), resp);
        }
        return SingleResponse.of(resp);
    }

    @ApiOperation(value = "课堂记录-课堂整体表现-课堂记录学生列表", notes = "课堂记录-课堂整体表现-课堂记录学生列表")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "QueryStudentAnalyzeReq")
    @PostMapping("/course/student/analyze")
    @ResponseBody
    public MultiResponse<StudentAnalyzeResp> courseStudentAnalyze(@RequestBody QueryStudentAnalyzeReq request) {
        QueryAnalysisClassCourseStudentListReq queryAnalysisClassCourseIdReq = new QueryAnalysisClassCourseStudentListReq();
        queryAnalysisClassCourseIdReq.setCourseId(request.getCourseId());
        if (!StringUtil.isEmpty(request.getXsxb())) {
            if (request.getXsxb().equals("1") || request.getXsxb().equals("2")) {
                queryAnalysisClassCourseIdReq.setGender(request.getXsxb());
            }
        }
        queryAnalysisClassCourseIdReq.setPage(request.getPageNo());
        queryAnalysisClassCourseIdReq.setLimit(request.getPageSize());
        ApiListResponse<ClassCourseAnalysisStudentListResp> response = xunFeiClassCourseAnalysisApiService.getAnalysisClassCourseStudentList(queryAnalysisClassCourseIdReq, getPartyId().toString(), null, getUserId().toString());
        if (null != response.getMsg() && response.getMsg().equals("success")) {
            List<StudentAnalyzeResp> list = BeanUtil.copyList(response.getData(), StudentAnalyzeResp.class);
            return MultiResponse.of(list, response.getTotal(), request);
        }
        return MultiResponse.of(new ArrayList<>(), 0, request);
    }

    @ApiOperation(value = "课堂记录-课堂整体表现-导出课堂记录学生列表", notes = "课堂记录-课堂整体表现-导出课堂记录学生列表")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "QueryStudentAnalyzeReq")
    @GetMapping("/course/student/analyzeExport")
    public void   courseStudentAnalyzeExport(@RequestParam String courseId,@RequestParam(required = false) String xsxb) {
        QueryStudentAnalyzeReq  request=new QueryStudentAnalyzeReq();
        request.setCourseId(courseId);
        request.setXsxb(xsxb);
        QueryAnalysisClassCourseStudentListReq queryAnalysisClassCourseIdReq = new QueryAnalysisClassCourseStudentListReq();
        queryAnalysisClassCourseIdReq.setCourseId(request.getCourseId());
        if (!StringUtil.isEmpty(request.getXsxb())) {
            if (request.getXsxb().equals("1") || request.getXsxb().equals("2")) {
                queryAnalysisClassCourseIdReq.setGender(request.getXsxb());
            }
        }
        queryAnalysisClassCourseIdReq.setPage(1);
        queryAnalysisClassCourseIdReq.setLimit(1000);
        ApiListResponse<ClassCourseAnalysisStudentListResp> response = xunFeiClassCourseAnalysisApiService.getAnalysisClassCourseStudentList(queryAnalysisClassCourseIdReq, getPartyId().toString(), null, getUserId().toString());
        if (null != response.getMsg() && response.getMsg().equals("success")) {
            List<StudentAnalyzeResp> list = BeanUtil.copyList(response.getData(), StudentAnalyzeResp.class);
            ExcelWriter writer = ExcelUtil.getWriter();
            writer.addHeaderAlias("studentName", "学生名称");
            writer.addHeaderAlias("ringNo", "手环编号");
            writer.addHeaderAlias("avgHeart", "平均心率");
            writer.addHeaderAlias("maxHeart", "最大心率");
            writer.addHeaderAlias("exerciseDensity", "运动密度");
            writer.addHeaderAlias("heartExponent", "心率指数");
            writer.addHeaderAlias("baseHeart", "基础心率平均值");
            writer.addHeaderAlias("targetHeartTime", "靶心率时间");
            writer.addHeaderAlias("sportTime", "运动时间");
            writer.addHeaderAlias("sportPower", "运动强度");
            writer.addHeaderAlias("maxLimitTime", "极限警示最大时长");
            writer.write(list, true);
            httpServletResponse.setContentType("application/vnd.ms-excel;charset=utf-8");
            httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + "analyzeExport" + ".xls");
            ServletOutputStream out = null;
            try {
                out = httpServletResponse.getOutputStream();
                writer.flush(out, true);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                writer.close();
            }
            IoUtil.close(out);
        }
    }


    @ApiOperation(value = "课堂记录-班级参数标准", notes = "课堂记录-班级参数标准")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "QueryCourseStandardReq")
    @PostMapping("/course/standard")
    @ResponseBody
    public MultiResponse<ClassCourseAnalysisStandardResp> courseStandard(@RequestBody QueryCourseStandardReq request) {
        QueryAnalysisClassCourseStandardReq req = new QueryAnalysisClassCourseStandardReq();
        req.setClassId(request.getClassId());
        req.setClassType(request.getClassType());
        ApiListResponse<ClassCourseAnalysisStandardResp> response = xunFeiClassCourseAnalysisApiService.getAnalysisCourseStandard(req, getPartyId().toString(), null, getUserId().toString());
        if (null != response.getMsg() && response.getMsg().equals("success")) {
            return MultiResponse.ofWithoutTotal(response.getData());
        }
        return MultiResponse.ofWithoutTotal(new ArrayList<>());
    }

    @ApiOperation(value = "课堂记录-课堂详情-达标学生", notes = "课堂记录-课堂详情-达标学生")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "QueryCourseAnalyzeReq")
    @PostMapping("/course/student/count")
    @ResponseBody
    public SingleResponse<CourseStudentCountResp> courseStudentCount(@RequestBody QueryCourseAnalyzeReq request) {
        CourseStudentCountResp courseStudentCountResp = new CourseStudentCountResp();
        QueryAnalysisClassCourseIdReq queryAnalysisClassCourseIdReq = new QueryAnalysisClassCourseIdReq();
        queryAnalysisClassCourseIdReq.setCourseId(request.getCourseId());
        ApiSingleResponse<ClassCourseAnalysisContentQuotaResp> response = xunFeiClassCourseAnalysisApiService.getAnalysisClassCourseContentQuota(queryAnalysisClassCourseIdReq, getPartyId().toString(), null, getUserId().toString());
        if (response.getMsg().equals("success")) {
            courseStudentCountResp.setExerciseDensityQualified(response.getData().getExerciseDensityQualified());
            courseStudentCountResp.setAvgHeartQualified(response.getData().getAvgHeartQualified());
            courseStudentCountResp.setMaxHeartQualified(response.getData().getMaxHeartQualified());
            courseStudentCountResp.setBaseHeartQualified(response.getData().getBaseHeartQualified());
            courseStudentCountResp.setHeartExponentQualified(response.getData().getHeartExponentQualified());
        }
        return SingleResponse.of(courseStudentCountResp);
    }


    @ApiOperation(value = "课堂记录-课堂详情-待优化学生明细", notes = "课堂记录-课堂详情-待优化学生明细")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "QueryCourseAnalyzeReq")
    @PostMapping("/course/student/info")
    @ResponseBody
    public MultiResponse<CourseStudentInfoResp> courseStudentInfo(@RequestBody QueryCourseAnalyzeReq request) {
        QueryAnalysisClassCourseIdReq queryAnalysisClassCourseIdReq = new QueryAnalysisClassCourseIdReq();
        queryAnalysisClassCourseIdReq.setCourseId(request.getCourseId());
        ApiListResponse<ClassCourseStudentQuotaResp> response = xunFeiClassCourseAnalysisApiService.getAnalysisClassCourseContentQuotaStudent(queryAnalysisClassCourseIdReq, getPartyId().toString(), null, getUserId().toString());
        if (null != response.getMsg() && response.getMsg().equals("success")) {
            List<CourseStudentInfoResp> resp = BeanUtil.copyList(response.getData(), CourseStudentInfoResp.class);
            return MultiResponse.ofWithoutTotal(resp);
        }
        return MultiResponse.ofWithoutTotal(new ArrayList<>());
    }

    @ApiOperation(value = "课堂记录-课堂详情-学生课堂表现-学生详情", notes = "课堂记录-课堂详情-学生课堂表现-学生详情")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "QueryOneStudentAnalyzeReq")
    @PostMapping("/course/student/one")
    @ResponseBody
    public SingleResponse<OneStudentAnalyzeResp> courseOneStudentAnalyze(@RequestBody QueryOneStudentAnalyzeReq request) {
        OneStudentAnalyzeResp resp = new OneStudentAnalyzeResp();
        QueryAnalysisClassCourseStudentReq queryAnalysisClassCourseIdReq = new QueryAnalysisClassCourseStudentReq();
        queryAnalysisClassCourseIdReq.setCourseId(request.getCourseId());
        queryAnalysisClassCourseIdReq.setStudentId(request.getStudentId());
        ApiSingleResponse<ClassCourseAnalysisStudentInfoResp> response = xunFeiClassCourseAnalysisApiService.getAnalysisClassCourseStudentInfo(queryAnalysisClassCourseIdReq, getPartyId().toString(), null, getUserId().toString());
        if (null != response.getMsg() && response.getMsg().equals("success") && ObjectUtils.isNotNull(response.getData())) {
            BeanUtil.copyProperties(response.getData(), resp);
        }
        return SingleResponse.of(resp);
    }


    @ApiOperation(value = "体育课堂-数据分析", notes = "体育课堂-数据分析")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "QueryClassCourseListReq")
    @PostMapping("/class/datacount/search")
    @ResponseBody
    public SingleResponse dataCountSearch(@RequestBody QueryClassCourseListReq request) {
        if (CollectionUtil.isEmpty(request.getClassIdList()) || request.getClassIdList().size() > 5) {
            return SingleResponse.buildFailure("班级选择错误");
        }
        QueryAnalysisClassCourseDataReq req = new QueryAnalysisClassCourseDataReq();
        req.setLimit(request.getSize().toString());
        req.setClassIds(Strings.join(request.getClassIdList(), ','));
        ApiListResponse<ClassCourseAnalysisDataResp> response = xunFeiClassCourseAnalysisApiService.getAnalysisClassCourseData(req, getPartyId().toString(), null, getUserId().toString());
        if (null != response.getMsg() && response.getMsg().equals("success")) {
            Map<String, List<ClassCourseAnalysisDataResp>> map = response.getData().stream().collect(Collectors.groupingBy(ClassCourseAnalysisDataResp::getClassName));
            return SingleResponse.of(map);
        }
        return SingleResponse.of(new HashMap<>());
    }

    @ApiOperation(value = "体育课堂-学期报告-分析数据", notes = "体育课堂-学期报告-分析数据")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "QueryByCycleClassReq")
    @PostMapping("/class/term/statistic")
    @ResponseBody
    public SingleResponse<TermStudentAnalyzeResp> classTermStatistic(@RequestBody QueryByCycleClassReq request) {
        TermStudentAnalyzeResp termStudentAnalyzeResp = new TermStudentAnalyzeResp();
        QueryAnalysisCycleClassCourseReq req = new QueryAnalysisCycleClassCourseReq();
        req.setCycleId(request.getCycleId());
        req.setClassId(request.getClassId());
        TeacherCycle teacherCycle=teacherCycleDao.selectById(Long.valueOf(request.getCycleId()));
        if(null == teacherCycle || System.currentTimeMillis()< teacherCycle.getCycleEndTime().getTime()){
            return  SingleResponse.buildSuccess();
        }
        ApiSingleResponse<ClassCourseAnalysisCycleResp> response = xunFeiClassCourseAnalysisApiService.getAnalysisClassCourseStatistic(req, getPartyId().toString(), null, getUserId().toString());
        if (null != response.getMsg() && !response.getMsg().equals("success")) {
            return SingleResponse.buildFailure(response.getMsg());
        }
        if (null == response.getData()) {
            return SingleResponse.buildSuccess();
        }
        BeanUtil.copyProperties(response.getData(), termStudentAnalyzeResp);
        termStudentAnalyzeResp.setCycleStartTime(teacherCycle.getCycleStartTime());
        termStudentAnalyzeResp.setCycleEndTime(teacherCycle.getCycleEndTime());
        termStudentAnalyzeResp.setReportTime(DateUtil.getAddDateTime(teacherCycle.getCycleEndTime(),72));
        return SingleResponse.of(termStudentAnalyzeResp);
    }

    @ApiOperation(value = "体育课堂-学期报告-学生列表", notes = "体育课堂-学期报告-学生列表")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "QueryClassTermStatisticReq")
    @PostMapping("/class/term/student/list")
    @ResponseBody
    public MultiResponse<StudentInfoResp> classTermStudentList(@RequestBody QueryByCycleClassReq request) {
        QueryAnalysisCycleClassCourseStudentReq req = new QueryAnalysisCycleClassCourseStudentReq();
        req.setCycleId(request.getCycleId());
        req.setClassId(request.getClassId());
        req.setPage(request.getPageNo());
        req.setLimit(request.getPageSize());
        ApiListResponse<ClassCourseAnalysisStudentStatisticListResp> response = xunFeiClassCourseAnalysisApiService.getAnalysisClassCourseStudentStatistic(req, getPartyId().toString(), null, getUserId().toString());
        if (null != response.getMsg() && response.getMsg().equals("success")) {
            List<StudentInfoResp> list = BeanUtil.copyList(response.getData(), StudentInfoResp.class);
            return MultiResponse.of(list, response.getTotal(), request);
        }
        return MultiResponse.of(new ArrayList<>(), 0, request);
    }

    @ApiOperation(value = "体育课堂-学期报告-学生详情", notes = "体育课堂-学期报告-学生详情")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "QueryOneStudentCycleAnalyzeReq")
    @PostMapping("/class/term/student")
    @ResponseBody
    public SingleResponse<CycleAnalysisStudentInfoResp> classTermStudent(@RequestBody QueryOneStudentCycleAnalyzeReq request) {
        CycleAnalysisStudentInfoResp resp = new CycleAnalysisStudentInfoResp();
        QueryAnalysisCycleStudentReq req = new QueryAnalysisCycleStudentReq();
        req.setCycleId(request.getCycleId());
        req.setStudentId(request.getStudentId());
        ApiSingleResponse<ClassCourseCycleAnalysisStudentInfoResp> response = xunFeiClassCourseAnalysisApiService.getAnalysisCycleStudentInfo(req, getPartyId().toString(), null, getUserId().toString());
        if (null != response.getMsg() && response.getMsg().equals("success") && ObjectUtils.isNotNull(response.getData())) {
            BeanUtil.copyProperties(response.getData(), resp);
        }
        return SingleResponse.of(resp);
    }
}
